import json
import os
import time
import subprocess
import re
import datetime as dt
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime

# 提示信息
print("=====注意：请先将电脑和面板连接在同一局域网下!!!!!=====")

order = 'adb shell top -n1'
cpulist = []
x_time = []
totalTime = 0
# 获取当前时间
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

# 创建一个图形和一个子图
fig, ax = plt.subplots()

# 在图表下方添加当前时间
# 在图表下方添加当前时间
plt.text(0.5, 0.05, f'Current Test Time: {current_time}',
         horizontalalignment='center',
         verticalalignment='center',
         transform=ax.transAxes,
         fontsize=5, color='black')

while(True):
    pi = subprocess.Popen(order, shell=True, stdout=subprocess.PIPE)
    cols = 0
    for i in iter(pi.stdout.readline,""):
        # 第五行开始为实际进程的CPU占用情况
        if cols >= 5:
            #print(i)
            if 'com.haier.uhome+' in str(i,'utf-8'):
                # 将多个空格转换为单空格，并按照空格切分字符串
                singleSpace = re.sub(' +', ' ', str(i,'utf-8')).split(' ')
                print(singleSpace)
                # 如果CPU占用低于50，则过滤掉
                if(float(singleSpace[9]) > 50.0):
                    # 记录纵坐标轴CPU参数
                    cpulist.append(float(singleSpace[9]))

                    # 记录横坐标轴时间参数
                    current_time = dt.datetime.now().strftime("%T")
                    x_time.append(current_time)
                    plt.title('Max:' + str(max(cpulist)) + "   Min:" + str(min(cpulist)) + "   Avg:" + "{:.2f}".format(sum(cpulist)/len(cpulist)) + "  Du:" + str(totalTime) + "sec")
                    plt.plot(x_time, cpulist, lw=1, ls='-', c='g')
                    plt.xticks([])

                    plt.pause(0.01)
                    #plt.plot()
                    #plt.show()
        cols = cols + 1
        if cols > 10:
            #print("\n")
            time.sleep(1)
            totalTime = totalTime + 1
            break;
